//
//  CJOAuthViewController.swift
//  SwiftDemo
//
//  Created by Chris on 2017/7/2.
//  Copyright © 2017年 chris. All rights reserved.
//

import UIKit
import SVProgressHUD

class CJOAuthViewController: UIViewController {

    fileprivate let webView = UIWebView()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        
        // 加载URL
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(CJAppKey)&redirect_uri=\(CJAppRedirectUri)"
        
        guard let url = URL(string: urlString) else {
            return
        }
        let request = URLRequest(url: url)
        
        webView.loadRequest(request)
    }

    /// 返回
    @objc fileprivate func back() {
        SVProgressHUD.dismiss()
        dismiss(animated: true, completion: nil)
    }
    
    /// 自动填充用户名和密码
    @objc fileprivate func autoFillForm() {
        let js = "document.getElementById('userId').value = '1178780126@qq.com';document.getElementById('passwd').value = 'a123456';"
        webView.stringByEvaluatingJavaScript(from: js)
    }
}

// MARK: - 界面设置
extension CJOAuthViewController {
    
    // MARK: -设置UI
    /// 设置UI
    fileprivate func setupUI() {
        
        
        view = webView
        view.backgroundColor = UIColor.white
        
        // 设置代理
        webView.delegate = self
        // 禁止scrollView滚动
        webView.scrollView.isScrollEnabled = false
        
        // 设置导航栏
        title = "登录"
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", target: self, action: #selector(back), isBack: true)
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", target: self, action: #selector(autoFillForm))
    }
}

extension CJOAuthViewController: UIWebViewDelegate {
    
    /// 拦截webview将要加载的请求
    ///
    /// - Parameters:
    ///   - webView: webview
    ///   - request: 将要加载的请求
    ///   - navigationType: 导航类型
    /// - Returns: webview是否要加载改请求
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        
//        if request.url?.absoluteString.hasPrefix(CJAppRedirectUri) == false {
//            return true
//        }
//        
//        if request.url?.absoluteString.contains("error") == false {
//            
//            print("取消授权")
//            back()
//            return false
//        }
//        
//        if request.url?.query?.hasPrefix("code=") == true {
//            
//            let code = request.url?.query?.substring(from: "code=".endIndex) ?? ""
//            
//            print("授权码 - " + code)
//        }
//        
//        return false
        
        // 微博界面
        if request.url?.absoluteString.hasPrefix("https://api.weibo.com/") == true {
            return true
        }
        // 授权成功
        if request.url?.absoluteString.hasPrefix(CJAppRedirectUri) == true {
            
            let code = request.url?.query?.substring(from: "code=".endIndex) ?? ""
            
            print("授权码 - " + code)
            
            // 获取accessToken
            CJNetworkManager.loadOAuthAccessToken(code: code, completion: { (isSuccess) in
                if isSuccess {
                    print("授权成功!")
                    SVProgressHUD.showInfo(withStatus: "授权成功!")
                    // 发送登陆成功通知
                    NotificationCenter.default.post(name: NSNotification.Name(rawValue: CJUserLoginSuccessNotification), object: self, userInfo: nil)
                    // 退出登录授权界面
                    self.back()
                } else {
                    print("网络请求失败!")
                    SVProgressHUD.showInfo(withStatus: "网络请求失败!")
                }
            })
            
            return false
        }
        // 授权失败
        if request.url?.query?.contains("error") == true {
            print("授权失败")
        }
        print("---- " + (request.url?.absoluteString ?? ""))
        back()
        return false
    }
    
    /// 开始加载页面
    func webViewDidStartLoad(_ webView: UIWebView) {
        SVProgressHUD.show()
    }
    /// 页面加载结束
    func webViewDidFinishLoad(_ webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
}
